/*
 * Flowmeter.h
 *
 *  Created on: 2015年7月31日
 *      Author: chuanjiang.zh@qq.com
 */

#ifndef FLOWMETER_H_
#define FLOWMETER_H_

#include "BasicType.h"
#include "TCriticalSection.h"
#include <time.h>
#include <deque>
#include <map>


/**
 * 流量统计 
 */
class Flowmeter
{
public:
    static const size_t DEF_WINDOW = 5;    /// 默认窗口,单位为秒 

public:
    Flowmeter();
    virtual ~Flowmeter();

    void count(int bytes);

    /// 单位 KBps
    double getRate();

    /// 获取平均位率 
    double getAvgRate();

    /// 获取总字节数 
    int64_t getTotalBytes();

    /// 清理 
    void clear();

    /**
     * 设置计算的窗口大小, 单位为秒 
     * @param seconds
     */
    void setWindow(size_t seconds);

    /**
     * 获取计算窗口 
     * @return
     */
    size_t getWindow();

    /**
     * 获取当前时钟值 
     * @return
     */
    int64_t getClock();

    /// 获取总的包数 
    int64_t getCounter();

    /// 获取丢失的包数 
    int64_t getLostCount();

    /// 丢失了多个媒体包 
    void    lostPacket(int count);

protected:
    void removeOutdated(int64_t clockNow);

private:
    typedef std::pair< int, int64_t >   Point;

    typedef std::deque< Point >   PointDeque;

    PointDeque  m_pointDeque;
    size_t  m_window;   /// 时间窗口，单位为毫秒 

    int64_t     m_tmfirst;
    int64_t     m_tmlast;

    int64_t     m_windowBytes;    /// 窗口字节数 

    int64_t     m_tmStart;
    int64_t     m_totalBytes;

    int64_t     m_counter;
    int64_t     m_lostCount;

    comn::CriticalSection   m_cs;

};

#endif /* FLOWMETER_H_ */
